//<MStar Software>
//******************************************************************************
// MStar Software
// Copyright (c) 2010 - 2015 MStar Semiconductor, Inc. All rights reserved.
// All software, firmware and related documentation herein ("MStar Software") are
// intellectual property of MStar Semiconductor, Inc. ("MStar") and protected by
// law, including, but not limited to, copyright law and international treaties.
// Any use, modification, reproduction, retransmission, or republication of all
// or part of MStar Software is expressly prohibited, unless prior written
// permission has been granted by MStar.
//
// By accessing, browsing and/or using MStar Software, you acknowledge that you
// have read, understood, and agree, to be bound by below terms ("Terms") and to
// comply with all applicable laws and regulations:
//
// 1. MStar shall retain any and all right, ownership and interest to MStar
//    Software and any modification/derivatives thereof.
//    No right, ownership, or interest to MStar Software and any
//    modification/derivatives thereof is transferred to you under Terms.
//
// 2. You understand that MStar Software might include, incorporate or be
//    supplied together with third party's software and the use of MStar
//    Software may require additional licenses from third parties.
//    Therefore, you hereby agree it is your sole responsibility to separately
//    obtain any and all third party right and license necessary for your use of
//    such third party's software.
//
// 3. MStar Software and any modification/derivatives thereof shall be deemed as
//    MStar's confidential information and you agree to keep MStar's
//    confidential information in strictest confidence and not disclose to any
//    third party.
//
// 4. MStar Software is provided on an "AS IS" basis without warranties of any
//    kind. Any warranties are hereby expressly disclaimed by MStar, including
//    without limitation, any warranties of merchantability, non-infringement of
//    intellectual property rights, fitness for a particular purpose, error free
//    and in conformity with any international standard.  You agree to waive any
//    claim against MStar for any loss, damage, cost or expense that you may
//    incur related to your use of MStar Software.
//    In no event shall MStar be liable for any direct, indirect, incidental or
//    consequential damages, including without limitation, lost of profit or
//    revenues, lost or damage of data, and unauthorized system use.
//    You agree that this Section 4 shall still apply without being affected
//    even if MStar Software has been modified by MStar in accordance with your
//    request or instruction for your use, except otherwise agreed by both
//    parties in writing.
//
// 5. If requested, MStar may from time to time provide technical supports or
//    services in relation with MStar Software to you for your use of
//    MStar Software in conjunction with your or your customer's product
//    ("Services").
//    You understand and agree that, except otherwise agreed by both parties in
//    writing, Services are provided on an "AS IS" basis and the warranty
//    disclaimer set forth in Section 4 above shall apply.
//
// 6. Nothing contained herein shall be construed as by implication, estoppels
//    or otherwise:
//    (a) conferring any license or right to use MStar name, trademark, service
//        mark, symbol or any other identification;
//    (b) obligating MStar or any of its affiliates to furnish any person,
//        including without limitation, you and your customers, any assistance
//        of any kind whatsoever, or any information; or
//    (c) conferring any license or right under any intellectual property right.
//
// 7. These terms shall be governed by and construed in accordance with the laws
//    of Taiwan, R.O.C., excluding its conflict of law rules.
//    Any and all dispute arising out hereof or related hereto shall be finally
//    settled by arbitration referred to the Chinese Arbitration Association,
//    Taipei in accordance with the ROC Arbitration Law and the Arbitration
//    Rules of the Association by three (3) arbitrators appointed in accordance
//    with the said Rules.
//    The place of arbitration shall be in Taipei, Taiwan and the language shall
//    be English.
//    The arbitration award shall be final and binding to both parties.
//
//******************************************************************************
//<MStar Software>

package com.homwee.factory;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.storage.StorageManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.homwee.factory.util.Contants;
import com.homwee.factory.util.PatternData;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

import com.homwee.tvap.common.comSettingInterface.factoryPage5;
import com.mediatek.twoworlds.factory.MtkTvFApiInformation;


/** RR-2114, add comments for mantis tracking */
public class TestImagePatternsActivity extends Activity {
    private final String LOG_TAG = "TestImagePatternsActivity";

    private final String PREFERENCES_TV_FACTORY = "tv-factory-menu";
    private final String PREFERENCES_KEY_IMAGE_ALPHA = "pattern-color-alpha";

    /** Built-in test color pattern */
    private final int[] PATTERN_LIST_PURE_COLOR = {
        R.drawable.pattern_color_red,
        R.drawable.pattern_color_green,
        R.drawable.pattern_color_blue,
        R.drawable.pattern_color_yellow,
        R.drawable.pattern_color_purple,
        R.drawable.pattern_color_lightgreen,
        R.drawable.pattern_color_white
    };

    /** Built-in test image pattern */
    private final int[] PATTERN_LIST_IMAGE = {
        R.drawable.pattern_image_greyscale256,
        R.drawable.pattern_image_greyscale16,
        R.drawable.pattern_image_colorstripe,
        R.drawable.pattern_image_colorarea,
        R.drawable.pattern_image_grey48,
        R.drawable.pattern_image_grey128
    };

    /** Built-in test local dimming test**/
    private final int[] PATTREN_LOCAL_DIMMING_TEST_IMAGE={
            R.drawable.pattern_local_dimming_test
    };
    /** Built-in local dimming aging pattern **/
    private final int[] PATTERN_LOCAL_DIMMING_AGING={
            R.drawable.pattern_color_white
    };

    private final int FOURK_WIDTH = 3840;
    private final int FOURK_HEIGHT = 2160;

    private final int PANEL_SHOW_DURATION_MILLIS = 5000;

    private StorageManager mStorageManager = null;
    private DiskChangeReceiver mDiskChangeReceiver;
    private List<PatternData> mImageList;

    private ImageView mBtnPrev;
    private ImageView mBtnNext;
    private ImageView mImageView;
    private TextView mBrightness;
    private LinearLayout mPanel;
    private LinearLayout mBrightnessPanel;

    private int mIndex;
    private int mAlphaSavedInPreference;
    private int mAlpha;
    private SharedPreferences mPreference;

    private int isDimmingTest=0;
    private int isAgingPattern=0;
    public static Context mContext;
    private final String TAG="CHFactory.TestImagePatternsActivity";

    private final Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext=this;

        mPreference = getSharedPreferences(PREFERENCES_TV_FACTORY, Context.MODE_PRIVATE);
        mAlpha = mPreference.getInt(PREFERENCES_KEY_IMAGE_ALPHA, 16);
        mAlphaSavedInPreference = mAlpha;
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);

        mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);

        setContentView(R.layout.image_show);

        mImageView = (ImageView) findViewById(R.id.imageView);
        mPanel = (LinearLayout) findViewById(R.id.button_panel);
        mBtnPrev = (ImageView) findViewById(R.id.previous);
        mBtnNext = (ImageView) findViewById(R.id.next);
        mBrightness = (TextView) findViewById(R.id.brightness);
        mBrightness.setText("100%");
        mBrightnessPanel = (LinearLayout) findViewById(R.id.brightness_panel);

        isDimmingTest=getIntent().getIntExtra("dimmingTest",-1);
        isAgingPattern=getIntent().getIntExtra("agingPattern",-1);
		Log.d("CHFactory.page8","dimming test"+isDimmingTest);

        resetImageList();
        initScanUsbThread(true);
        if(isAgingPattern==1){
            checkAgingMode();
        }

        displayImage();
    }

    private void resetImageList() {
        mIndex = 0;

        mImageList = new ArrayList<PatternData>();

        if(isDimmingTest>0){
            for(int index =0;index<PATTREN_LOCAL_DIMMING_TEST_IMAGE.length;index++){
             mImageList.add(new PatternData(PatternData.TYPE_PATTERN_IMAGE_DEFAULT , PATTREN_LOCAL_DIMMING_TEST_IMAGE[index]));
			 mPanel.setVisibility(View.GONE);
            }
        }else if(isAgingPattern>0){
                mImageList.add(new PatternData(PatternData.TYPE_PATTERN_IMAGE_DEFAULT, PATTERN_LOCAL_DIMMING_AGING[0]));
                mPanel.setVisibility(View.GONE);
        }else {
            for (int index = 0; index < PATTERN_LIST_PURE_COLOR.length; index++) {
                mImageList.add(new PatternData(PatternData.TYPE_PATTERN_PURE_COLOR, PATTERN_LIST_PURE_COLOR[index]));
            }

            for (int index = 0; index < PATTERN_LIST_IMAGE.length; index++) {
                mImageList.add(new PatternData(PatternData.TYPE_PATTERN_IMAGE_DEFAULT, PATTERN_LIST_IMAGE[index]));
            }
        }
    }

    private void findPatternPicFolder(File folder) {
        if (folder == null) {
            return;
        }
        for (File file: folder.listFiles()) {
            if (file.isDirectory()) {
                String[] array = file.getAbsolutePath().split("/");
                if (array[array.length - 1].equalsIgnoreCase("pattern_pic")) {
                    scanPatternPics(file);
                    return;
                } else {
                    findPatternPicFolder(file);
                }
            }
        }
    }

    private void scanPatternPics(File folder) {
        if (folder == null) {
            return;
        }
        for (File file: folder.listFiles(new ImageFileFilter())) {
            if (file.isDirectory()) {
                scanPatternPics(file);
            } else {
                mImageList.add(new PatternData(PatternData.TYPE_PATTERN_IMAGE_EXTENDED, file.getAbsolutePath()));
            }
        }
    }

    private void initScanUsbThread(final boolean isFirstTimeScan) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                /** External storage only needs to be scanned 1 time */
                if (isFirstTimeScan) {
					if(getExternalFilesDir(null) != null){
                   // if (Environment.getExternalStorageDirectory() != null) {
                   //findPatternPicFolder(new File(Environment.getExternalStorageDirectory().getAbsolutePath()));
						findPatternPicFolder(new File(getExternalFilesDir(null).getAbsolutePath()));
                    }
                }

                /** USB storage needs to be scanned every time */
                /**
                 * FIXME: Hard-code usb path for AN 6.0 for now
                 * need to add other implementations for other AN versions
                 * will be required on 8.0+
                 */
                findPatternPicFolder(new File("/mnt/usb/"));
            }
        }).start();
    }

    // private StorageVolume getExternalStorageVolumeInfo() {
    //     List<StorageVolume> volumeList = mStorageManager.getStorageVolumes();
    //     for (final StorageVolume vol : volumeList) {
    //         final StorageVolume storageVolume = vol;
    //         if ((true == vol.isRemovable()) && (false == vol.isEmulated())) {
    //             String uuid = vol.getUuid();
    //             if (null != uuid) {
    //                 return vol;
    //             }
    //         }
    //     }

    //     return null;
    // }

    @Override
    protected void onResume() {
        super.onResume();

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        filter.addAction(Intent.ACTION_MEDIA_EJECT);
        filter.addDataScheme("file");
        mDiskChangeReceiver = new DiskChangeReceiver();
        registerReceiver(mDiskChangeReceiver, filter);
    }

    @Override
    protected void onPause() {
        unregisterReceiver(mDiskChangeReceiver);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mAlphaSavedInPreference != mAlpha) {
            SharedPreferences.Editor editor = mPreference.edit();
            editor.putInt(PREFERENCES_KEY_IMAGE_ALPHA, mAlpha);
            editor.apply();
        }
        super.onDestroy();
    }


    private void displayImage() {
        if (mImageList == null) {
            return;
        }

        switch (mImageList.get(mIndex).getType()) {
            case PatternData.TYPE_PATTERN_PURE_COLOR:
                adjustAlpha(mAlpha);
                mBrightnessPanel.setVisibility(View.VISIBLE);
                mImageView.setImageResource(mImageList.get(mIndex).getResId());
                break;
            case PatternData.TYPE_PATTERN_IMAGE_DEFAULT:
                adjustAlpha(16);
                mBrightnessPanel.setVisibility(View.GONE);
                mImageView.setImageResource(mImageList.get(mIndex).getResId());
                break;
            case PatternData.TYPE_PATTERN_IMAGE_EXTENDED:
                adjustAlpha(16);
                mBrightnessPanel.setVisibility(View.GONE);
                Bitmap image;

                try {
                    image = BitmapFactory.decodeFile(mImageList.get(mIndex).getPath());
                    int w = image.getWidth();
                    int h = image.getHeight();
                    float aspRat = (float) w / (float) h;
                    Log.d (LOG_TAG, "original size: w = " + w + " , h = " + h + ", aspRat = " + aspRat);
                    if (w > FOURK_WIDTH) {
                        w = FOURK_WIDTH;
                        h = (int) (w / aspRat);
                    }
                    if (h > FOURK_HEIGHT) {
                        h = FOURK_HEIGHT;
                        w = (int) (h * aspRat);
                    }
                    Log.d (LOG_TAG, "size after adjusted: w = " + w + " , h = " + h + ", aspRat = " + aspRat);

                    Log.d (LOG_TAG, "createScaledBitmap ++ , mIndex = " + mIndex);
                    Bitmap b = Bitmap.createScaledBitmap(image, w, h, false);
                    Log.d (LOG_TAG, "createScaledBitmap --");
                    mImageView.setImageBitmap(b);
                    image = null;
                } catch (Exception e) {
                    Toast.makeText(TestImagePatternsActivity.this, "Error while image decoding, please report to developer.", Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                } finally {
                    image = null;
                }

                break;
        }
    }

    private void adjustAlpha(int alphaIndex) {
        float alpha = ((float) alphaIndex) / 16.0f;
        mImageView.setAlpha(alpha);
        mBrightness.setText(String.valueOf((int) (alpha * 100 + 0.5)) + "%");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
            case KeyEvent.KEYCODE_MENU:
                TestImagePatternsActivity.this.finish();
                break;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                mBtnPrev.setImageResource(R.drawable.icon_previous_focus);
                return true;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                mBtnNext.setImageResource(R.drawable.icon_next_focus);
                return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_LEFT:
                showPanel();
                mBtnPrev.setImageResource(R.drawable.icon_previous);
                if (mIndex == 0) {
                    mIndex = mImageList.size() - 1;
                } else {
                    mIndex --;
                }
                displayImage();
                return true;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                showPanel();
                mBtnNext.setImageResource(R.drawable.icon_next);
                if (mIndex == mImageList.size() - 1) {
                    mIndex = 0;
                } else {
                    mIndex ++;
                }
                displayImage();
                return true;
            case KeyEvent.KEYCODE_DPAD_UP:
            case KeyEvent.KEYCODE_DPAD_DOWN:
                if (mImageList.get(mIndex).getType() != PatternData.TYPE_PATTERN_PURE_COLOR) {
                    break;
                }
                showPanel();
                boolean isAlphaChanged = false;
                if (keyCode == KeyEvent.KEYCODE_DPAD_UP && mAlpha < 16) {
                    mAlpha ++;
                    isAlphaChanged = true;
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN && mAlpha > 0) {
                    mAlpha --;
                    isAlphaChanged = true;
                }

                if (isAlphaChanged) {
                    adjustAlpha(mAlpha);
                    return true;
                }
                break;
        }

        return super.onKeyUp(keyCode, event);
    }

    private void showPanel() {
        if (mPanel.getVisibility() != View.VISIBLE) {
            mPanel.setVisibility(View.VISIBLE);
        }
        scheduleHidePanel();
    }

    private void scheduleHidePanel() {
        mHandler.removeCallbacks(mHideRunnable);
        mHandler.postDelayed(mHideRunnable, PANEL_SHOW_DURATION_MILLIS);
    }

    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            mPanel.setVisibility(View.GONE);
        }
    };

    private class DiskChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
                Toast.makeText(TestImagePatternsActivity.this, "Usb storage removed!", Toast.LENGTH_SHORT).show();
                resetImageList();
                displayImage();
            } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
                Toast.makeText(TestImagePatternsActivity.this, "Usb storage mounted!", Toast.LENGTH_SHORT).show();
                initScanUsbThread(false);
            }
        }
    }

    public void checkAgingMode() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    int mode = MtkTvFApiInformation
                            .getInstance()
                            .getIniParameter(Contants.KEYSTATUS_INI_FILEPATH,
                                    Contants.FACTORY_AGE_MODE).equalsIgnoreCase("1") ? 1
                            : 0;

                    if(mode==0){
                        finish();
                        break;
                    }else{
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();

    }

    public class ImageFileFilter implements FileFilter {

        private String[] extension = {".jpg", "jpeg", ".bmp", ".png", ".gif"};

        @Override
        public boolean accept(File pathname) {
            if (pathname.isDirectory() && !pathname.isHidden()) {
                return true;
            }
            for (String ext : extension) {
                if (pathname.getName().toLowerCase().endsWith(ext)) {
                    return true;
                }
            }
            return false;
        }
    }
}
